'''
做自动登录滑动滑块验证的方法
'''
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from PIL import Image
import numpy as np
import cv2
from io import BytesIO
import time

def screenshot_element(driver, element):
    """截取指定元素的屏幕截图"""
    location = element.location
    size = element.size
    png = driver.get_screenshot_as_png()
    image = Image.open(BytesIO(png))
    left = location['x']
    top = location['y']
    right = left + size['width']
    bottom = top + size['height']
    return image.crop((left, top, right, bottom))

def get_images(driver):
    """获取滑块和拼图的图像"""
    slider = driver.find_element(By.XPATH, '//div[@class="slide-verify-slider-mask-item"]')
    puzzle = driver.find_element(By.XPATH, '//div[@id="slideVerify"]/canvas[1]')
    slider_image = screenshot_element(driver, slider)
    puzzle_image = screenshot_element(driver, puzzle)
    slider_np = np.array(slider_image)
    puzzle_np = np.array(puzzle_image)
    return slider_np, puzzle_np

def find_gap(slider_img, puzzle_img):
    """使用模板匹配找到拼图缺口的位置"""
    slider_gray = cv2.cvtColor(slider_img, cv2.COLOR_BGR2GRAY)
    puzzle_gray = cv2.cvtColor(puzzle_img, cv2.COLOR_BGR2GRAY)
    result = cv2.matchTemplate(slider_gray, puzzle_gray, cv2.TM_CCOEFF_NORMED)
    _, max_val, _, max_loc = cv2.minMaxLoc(result)
    return max_loc

def slide_slider(driver, gap_location):
    """模拟滑块滑动操作"""
    slider = driver.find_element(By.XPATH, '//div[@class="slide-verify-slider-mask-item"]')
    action = ActionChains(driver)
    action.click_and_hold(slider).perform()
    distance = gap_location[0]
    action.move_by_offset(distance, 0).perform()
    action.release().perform()

def main(driver):
    """主函数执行滑块验证"""
    attempt = 1
    try:
        while '我的用户' not in driver.page_source:
            slider_np, puzzle_np = get_images(driver)
            gap_location = find_gap(slider_np, puzzle_np)
            slide_slider(driver, gap_location)
            attempt += 1
            time.sleep(0.5)
    except Exception as e:
        pass
    print(f'共尝试第 {attempt} 次滑动滑动识别完成')

    # attempt = 1
    #
    # while True:
    #     slider_np, puzzle_np = get_images(driver)
    #     gap_location = find_gap(slider_np, puzzle_np)
    #     slide_slider(driver, gap_location)
    #     time.sleep(0.5)
    #     if "语音卡" in driver.page_source:
    #         print(f'共尝试 {attempt} 次，滑动识别完成')
    #         break
    #     attempt += 1

    # if '语音卡' in driver.page_source:
    #     print(f'共尝试 {attempt} 次，滑动识别完成')
    # else:
    #     print(f'达到最大尝试次数 {max_attempts}，识别未完成')

